﻿using B.S.Material.Domain.BOM;
using B.S.Material.ErrorCode;
using B.S.Material.Read.Api.Applications.Command.MaterialsPickingCommand;
using MediatR;
using SqlSugar;

namespace B.S.Material.Read.Api.Applications.Handler.MaterialsPickingHandelr
{
    public class GetMaterialsPickingHandelr : IRequestHandler<GetMaterialsPickingCommand, ApiResult<ApiPaging<MaterialsPicking>>>
    {
        private readonly ISqlSugarClient db;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        /// <param name="config"></param>
        public GetMaterialsPickingHandelr(ISqlSugarClient db)
        {
            this.db = db;

        }

        public async Task<ApiResult<ApiPaging<MaterialsPicking>>> Handle(GetMaterialsPickingCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<MaterialsPicking>> result = new ApiResult<ApiPaging<MaterialsPicking>>();

            var list = await db.Queryable<MaterialsPicking>().Where(x => !x.IsDel).ToListAsync();

            //条件查询

            if (!string.IsNullOrEmpty(request.RelatedProject))
            {
                list = list.Where(x => x.RelatedProject.Contains(request.RelatedProject)).ToList();
            }
            if (!string.IsNullOrEmpty(request.DocumentSubject))
            {
                list = list.Where(x => x.DocumentSubject.Contains(request.DocumentSubject)).ToList();
            }
            if (!string.IsNullOrEmpty(request.DocumentNo))
            {
                list = list.Where(x => x.DocumentNo == request.DocumentNo).ToList();
            }
            if (request.PickingDate != null)
            {
                list = list.Where(x => x.PickingDate.Date == request.PickingDate.Value.Date).ToList();
            }
            if (!string.IsNullOrEmpty(request.ProduceName))
            {
                list = list.Where(x => x.ProduceName.Contains(request.ProduceName)).ToList();
            }
            int totalCount = list.Count();
            int PageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            list = list.OrderByDescending(a => a.PickingId).Skip((request.pageindex - 1) * request.pageSize).Take(request.pageSize).ToList();
            ApiPaging<MaterialsPicking> paging = new ApiPaging<MaterialsPicking>()
            {
                totalCount = totalCount,
                PageCount = PageCount,
                Result = list.ToList(),
            };

            result.Code = ApiEnum.显示成功;
            result.MAG = ApiEnum.显示成功.ToString();
            result.data = paging;
            return result;

        }
    }

}
